package cn._2dland.comment
{
	import cn._2dland.comment.locator.CommentLocator;
	import cn._2dland.comment.locator.CommentLocatorFactory;
	import cn._2dland.events.CommentEvent;
	import cn._2dland.net.CommentLoader;
	import cn._2dland.utils.CommentUtils;
	import cn._2dland.utils.SortedLinkedList;
	
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;

	[Event(name="complete", type="flash.events.Event")]

	/**
	 * 评论控制类
	 * 负责加载和调度评论
	 * @author deadblue
	 */
	public class CommentController extends EventDispatcher
	{
		private var _loader:CommentLoader = null;
		private var _view:CommentView = null;

		private var _list:SortedLinkedList = null;

		public function CommentController(view:CommentView) {
			this._view = view;
		}

		/**
		 * 加载弹幕
		 * @param vid
		 */		
		public function loadComment(vid:String, remote:Boolean=false):void {
			if(_loader == null) initLoader();
			_loader.load(vid, remote);
		}

		/**
		 * 开始播放
		 */
		public function play():void {
			_view.play();
		}

		/**
		 * 暂停播放
		 */
		public function pause():void {
			_view.pause();
		}

		/**
		 * 更新
		 */
		public function update(time:Number):void {
			var cmnts:Array = _list.getDatas({playTime:time});

			for(var i:int=0; i<cmnts.length; i++){
				var cmntObj:CommentObject = cmnts[i] as CommentObject;
				_view.addComment(cmntObj);
			}
		}

		/**
		 * 定位
		 */
		public function seek(time:Number):void {
			_list.seek({playTime:time});
		}

		/**
		 * 获取弹幕列表
		 * @return 
		 */		
		public function get comments():Array {
			return _comments;
		}

		private function initLoader():void {
			if(_loader != null) return;
			
			_loader = new CommentLoader();
			_loader.addEventListener(Event.COMPLETE, commentCompleteHandler);
			_loader.addEventListener(ErrorEvent.ERROR, commentErrorHandler);
		}

		private function releaseLoader():void {
			if(_loader == null) return;

			_loader.removeEventListener(Event.COMPLETE, commentCompleteHandler);
			_loader.removeEventListener(ErrorEvent.ERROR, commentErrorHandler);
			_loader = null;
		}

		protected function commentCompleteHandler(e:Event):void {
			var cmnts:XMLList = _loader.commentXML.comment;
			_list = new SortedLinkedList(new CommentCompareRule());
			_comments = new Array();

			for(var i:int=0; i<cmnts.length(); i++){
				var cmntXML:XML = cmnts[i] as XML;
				var cmntObj:Object = CommentUtils.parseCommentXML(cmntXML);
				_list.add(cmntObj);
				_comments.push(cmntObj);
			}

			dispatchEvent(new Event(Event.COMPLETE));
			releaseLoader();
		}

		protected function commentErrorHandler(e:ErrorEvent):void {
			releaseLoader();
		}
	}
}